package com.example.application.views.weather;

import com.example.application.Bean.ResultBean;
import com.example.application.views.main.MainView;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.awt.*;
import java.awt.geom.Area;

@Route(value = "weather",layout = MainView.class)
@PageTitle("天气信息")
public class WeatherView extends Div {

    ComboBox<String>  city;

    Div div;

    public WeatherView(){

        div = new Div();

        city = new ComboBox<>();
        city.setItems("成都市", "绵阳市", "乐山市","哈尔滨");
        city.setValue("成都市");

        ObjectMapper objectMapper = new ObjectMapper();

       city.addValueChangeListener((e)->{

          String json =  getWeather(e.getValue());

          // JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ResultBean.class);

           try {
               ResultBean resultBean = objectMapper.readValue(json,ResultBean.class);

               System.out.println(resultBean);

               div.setText(resultBean.getLives().get(0).getProvince()+" "+resultBean.getLives().get(0).getCity()+" "+resultBean.getLives().get(0).getWeather()+"   "+resultBean.getLives().get(0).getTemperature()+"°C，最新更新时间："+resultBean.getLives().get(0).getReporttime());

           } catch (JsonProcessingException jsonProcessingException) {
               jsonProcessingException.printStackTrace();
           }


       });

        add(city,div);
    }


    private   String getWeather(String val) {

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet("https://restapi.amap.com/v3/weather/weatherInfo?key=c3d6bf904e408caaec2f8a09e0e5a2ab&city="+val);
            CloseableHttpResponse execute = client.execute(httpGet);
            String json = EntityUtils.toString(execute.getEntity(), "utf-8");
            System.out.println(json);

            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
}
